package com.yy.controller.ForegroundController;

import com.yy.config.R;
import com.yy.domain.Account;
import com.yy.domain.User;
import com.yy.service.ForegroundService.IUserService;
import com.yy.service.ForegroundService.impl.EmailServiceImpl;
import com.yy.utils.Mail;
import com.yy.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 发送邮件接口
 */
@RestController
@RequestMapping(value = "/email")
public class EmailController {

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private EmailServiceImpl emailService;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private IUserService userService;
    // 验证码存储
    HashMap<String,String> CodeMap = new HashMap<>();
    /**
     * 发送邮件，注册
     * @param mailTo
     * @return
     */
    @RequestMapping(value = "/sendMail",method = RequestMethod.GET)
    public String sendMail(String mailTo) throws MessagingException {
        //生成验证码
        String sources = "0123456789"; // 加上一些字母，就可以生成pc站的验证码了
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++){
            flag.append(sources.charAt(rand.nextInt(9)) + "");
        }
        String verifycode = flag.toString();
        //设置邮件内容
        String mailText = "【集市交易】 验证码："+verifycode+"   您正在注册集市交易网站账号，请勿将验证码告诉他人哦。";

        Mail mail = new Mail();
        mail.setRecipient(mailTo);// 设置收件人
        mail.setSubject("集市交易平台");// 设置邮件主题
        mail.setContent(mailText);// 设置邮件内容
        mailUtil.sendSimpleMail(mail);

        return verifycode;
    }


    /**
     * 发送邮件，商品出售
     * @param map
     */
    @RequestMapping(value = "/sendMailToUser",method = RequestMethod.POST)
    public void sendMailToUser(@RequestBody Map<String,Object> map){

        List<Map<String,String>> list = emailService.selectProductDetail(map);
        for (Map<String, String> arr:list) {
            String mailText = "您在【二手市场】网站发布的《"+arr.get("name")+"》已出售";
            toMail(arr.get("mail").toString(),mailText);
        }
    }


    /**
     * 发送邮件，商品状态更改
     * @param map
     */
    @RequestMapping(value = "/sendMailToBuyer",method = RequestMethod.POST)
    public void sendMailToBuyer(@RequestBody Map<String,Object> map){
        Map<String,String> MapObject = emailService.selectProductDetailByOrder(map);
        int type = (int) map.get("status");
        if(type == 2){
            String mailText = "【二手市场】您购买的《"+MapObject.get("name")+"》已发货";
            toMail(MapObject.get("mail"),mailText);
        }else if(type == 3){
            String mailText = "【二手市场】您发布的《"+MapObject.get("name")+"》已送达";
            toMail(MapObject.get("mail"),mailText);
        }else if(type == 4){
            String mailText = "【二手市场】您出售的《"+MapObject.get("name")+"》正在申请退款，请及时处理！";
            toMail(MapObject.get("mail"),mailText);
        }else if(type == 5){
            String mailText = "【二手市场】您购买的《"+MapObject.get("name")+"》退款成功！";
            toMail(MapObject.get("mail"),mailText);
        }else if(type == 6){
            String mailText = "【二手市场】您购买的《"+MapObject.get("name")+"》退款失败！";
            toMail(MapObject.get("mail"),mailText);
        }
    }


    /**
     * 发送邮件，公共方法
     * @param mailTo
     * @param mailText
     */
    public void toMail(String mailTo,String mailText){
        //定义发送标题
        String title = "二手交易市场";
        //设置发送方
        String mailFrom = "t18713827231@163.com";
        try {
            //构建邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            //设置邮件主题
            message.setSubject(title);
            //设置邮件发送者
            message.setFrom(mailFrom);
            //设置邮件接收者
            message.setTo(mailTo);
            //设置邮件发送日期
            message.setSentDate(new Date());
            //设置邮件正文
            message.setText(mailText);
            //发送邮件
            javaMailSender.send(message);
        }catch (Exception e){
            System.out.println(e);
        }
    }

    @GetMapping(value = "/sendResetCode")
    public R resetPassword(String mailTo){
        Boolean email = isEmail(mailTo);
        if (!email){
            return R.fail("请输入正确的邮箱");
        }
        //生成验证码
        String sources = "0123456789";
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++){
            flag.append(sources.charAt(rand.nextInt(9)) + "");
        }
        String verifycode = flag.toString();
        //设置邮件内容
        String mailText = "您当前正在重置密码您的验证码为："+verifycode+"，请勿将验证码告诉他人哦，如果非本人操作请前往平台修改密码!";
        if(!mailTo.isEmpty()){
            toMail(mailTo,mailText);
        }else{
            verifycode=null;
        }
        // 将验证码存入map中（我想有过期时间为1分钟 超过后自动移除）
        CodeMap.put(mailTo,verifycode);
        // 超过10条移除第一个
        if(CodeMap.size()>10){
            CodeMap.remove(mailTo);
        }
        //遍历打印 map
        for (Map.Entry<String, String> entry : CodeMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        return R.ok("验证码发送成功！",verifycode);
    }


    // 重置密码
    @GetMapping(value = "/resetPassword")
    public R resetPassword(String mailTo,String code){

        if(mailTo.isEmpty()){
            return R.fail("请输入邮箱");
        }
        if(code.isEmpty()){
            return R.fail("请输入验证码");
        }
        // 校验验证码
        if(!code.equals(CodeMap.get(mailTo))){
            return R.fail("验证码错误");
        }
        //查找用户
        User user = userService.selectUserBymail(mailTo);
        String username = user.getUsername();
        if(username.isEmpty()){
            return R.fail("用户不存在");
        }
        //查找账号
        Account account = userService.selectAccountByUserName(username);

        // 验证码正确，重置密码
        userService.restAccountById(account.getUserid());
        //移除验证码
        CodeMap.remove(mailTo);
        //遍历打印 map
        for (Map.Entry<String, String> entry : CodeMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
        }
        // 返回成功
        return R.ok("密码重置成功");
    }
    // 校验邮箱格式
    public Boolean isEmail(String email){
        String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        return Pattern.compile(regex).matcher(email).matches();
    }
}
